package com.qd.system.service.role;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.role.RoleMenuDTO;
import com.qd.common.sys.domain.entity.role.RoleMenuRelationsDTO;
import com.qd.system.mapper.RoleMenuMapper;
import com.qd.system.model.Role;
import com.qd.system.model.RoleMenu;
import com.qd.system.service.menu.MenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RoleMenuService extends BaseService<RoleMenuMapper, RoleMenu> {

    private static final String PREFIX_ID = "sys_role_menu_roleMenuId_{0}";
    private static final String PREFIX_ROLE_ID = "sys_role_menu_roleId_{0}";

    private final RedisTemplateUtil<RoleMenu> redisTemplateUtil;
    private final RoleService roleService;
    private final MenuService menuService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public RoleMenuDTO save(RoleMenuDTO dto) {
        final RoleMenu model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public RoleMenuDTO update(RoleMenuDTO dto) {
        final RoleMenu historyModel = Optional.ofNullable(getById(dto.getRoleMenuId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final RoleMenu model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<RoleMenu> mList) throws ApiException {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 删除，单个
     *
     * @param roleMenuId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String roleMenuId) {
        final RoleMenu model = Optional.ofNullable(getById(roleMenuId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(roleMenuId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<RoleMenu> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(RoleMenuDTO dto) {
        final QueryWrapper<RoleMenu> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param roleMenuId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String roleMenuId) {
        boolean exists = false;
        if (StringUtils.hasLength(roleMenuId)) {
            final RoleMenu model = getById(roleMenuId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param roleMenuId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public RoleMenu getById(String roleMenuId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, roleMenuId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(roleMenuId), RoleMenu.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param roleMenuId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public RoleMenuDTO getByIdDto(String roleMenuId) {
        final RoleMenu model = getById(roleMenuId);
        if (null != model) {
            return modelToDto(model);
        }
        return null;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public RoleMenu getOne(RoleMenuDTO dto) {
        final QueryWrapper<RoleMenu> queryWrapper = createQueryWrapper(dto);
        final RoleMenu model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public RoleMenuDTO getOneDto(RoleMenuDTO dto) {
        final RoleMenu model = getOne(dto);
        if (null == model) {
            return null;
        }
        final RoleMenuDTO newDto = modelToDto(model);
        model.freeData();
        return newDto;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<RoleMenu> getList(RoleMenuDTO dto) {
        final QueryWrapper<RoleMenu> queryWrapper = createQueryWrapper(dto);
        final List<RoleMenu> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<RoleMenuDTO> getListDto(RoleMenuDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<RoleMenuDTO> page(Page<RoleMenu> page, RoleMenuDTO dto) {
        final QueryWrapper<RoleMenu> queryWrapper = createQueryWrapper(dto);
        final IPage<RoleMenu> iPage = super.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage.convert(this::modelToDto);
    }


    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    @Transactional(readOnly = true)
    public void clearCache(RoleMenu model) {
        String roleId = model.getRoleId();
        final String roleMenuId = model.getRoleMenuId();
        if (!StringUtils.hasLength(roleId)) {
            final RoleMenu roleMenu = getById(roleMenuId);
            if (roleMenu != null) {
                roleId = roleMenu.getRoleId();
                roleMenu.freeData();
            }
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, roleMenuId));
        if (StringUtils.hasLength(roleId)) {
            redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ROLE_ID, roleId));
        }
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<RoleMenu> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        list.forEach(this::clearCache);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public RoleMenuDTO modelToDto(RoleMenu model) {
        if (null == model) {
            return null;
        }
        final RoleMenuDTO dto = new RoleMenuDTO();
        dto.setRoleMenuId(model.getRoleMenuId());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setRoleId(model.getRoleId());
        dto.setMenuId(model.getMenuId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public RoleMenu dtoToModel(RoleMenuDTO dto) {
        if (null == dto) {
            return null;
        }
        final RoleMenu model = new RoleMenu();
        model.setRoleMenuId(dto.getRoleMenuId());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setRoleId(dto.getRoleId());
        model.setMenuId(dto.getMenuId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(RoleMenuDTO dto) {
        dto.setRoleIdDisplay(roleService.idToDisplay(dto.getRoleId()));
        dto.setMenuIdDisplay(menuService.idToDisplay(dto.getMenuId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<RoleMenuDTO> modelToDtoList(List<RoleMenu> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<RoleMenu> dtoToModelList(List<RoleMenuDTO> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<RoleMenu> createQueryWrapper(RoleMenuDTO dto) {
        final QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(dto.getRoleId())) {
                queryWrapper.eq(Constants.ROLE_ID, dto.getRoleId());
            }
            if (StringUtils.hasLength(dto.getMenuId())) {
                queryWrapper.eq(Constants.MENU_ID, dto.getMenuId());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<RoleMenu> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<RoleMenu> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(RoleMenu::getRoleMenuId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 根据人员ID获得对应的权限信息
     *
     * @param personId 人员ID
     * @return 权限集合
     */
    public List<String> getMenuPermsByPersonId(String personId) {
        return super.getBaseMapper().getMenuPermsByPersonId(personId);
    }

    /**
     * 根据角色信息获得对应的菜单信息
     *
     * @param roleId 角色ID
     * @return 菜单信息
     */
    public List<RoleMenu> getMenuByRoleId(String roleId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ROLE_ID, roleId);
        return redisTemplateUtil.getList(new CacheKey().setKey(key), () -> list(new QueryWrapper<RoleMenu>().eq(Constants.ROLE_ID, roleId)), RoleMenu.class);
    }

    /**
     * 根据角色信息获得对应的菜单信息
     *
     * @param roleId 角色ID
     * @return 菜单信息
     */
    public List<String> getMenuStrByRoleId(String roleId) {
        final Role role = roleService.getById(roleId);
        if (role == null) {
            throw new ApiException("角色ID不存在[" + roleId + "]");
        }
        role.freeData();
        final List<RoleMenu> roleMenus = getMenuByRoleId(roleId);
        if (roleMenus.isEmpty()) {
            return Collections.emptyList();
        }
        return roleMenus.stream().map(RoleMenu::getMenuId).collect(toList());
    }

    /**
     * 检查菜单是否存在角色
     *
     * @param menuId 菜单ID
     * @return 是否存在
     */
    public boolean checkMenuExistRole(String menuId) {
        final QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.MENU_ID, menuId);
        final Long count = super.getBaseMapper().selectCount(queryWrapper);
        queryWrapper.clear();
        return null != count && count > 0;
    }

    /**
     * 根据角色ID和菜单ID获得角色和菜单对象
     *
     * @param roleId 角色ID
     * @param menuId 菜单ID
     * @return 角色和菜单对象
     */
    public RoleMenu getRoleMenuByRoleIdAndMenuId(String roleId, String menuId) {
        final QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.ROLE_ID, roleId);
        queryWrapper.eq(Constants.MENU_ID, menuId);
        final RoleMenu roleMenu = getOne(queryWrapper, false);
        queryWrapper.clear();
        return roleMenu;
    }

    @Transactional(readOnly = true)
    public void clearCacheByRoleId(String roleId) {
        final List<RoleMenu> list = getMenuByRoleId(roleId);
        list.forEach(this::clearCache);
    }


    @Transactional(rollbackFor = Exception.class)
    public void setRoleMenuRelations(RoleMenuRelationsDTO RoleMenuRelationsDTO) {
        final List<String> menuList = RoleMenuRelationsDTO.getMenuList();
        final String roleId = RoleMenuRelationsDTO.getRoleId();
        //按角色查询已经设置了菜单信息
        final List<String> existsRoleMenuList = getMenuStrByRoleId(roleId);
        if (!existsRoleMenuList.isEmpty()) {
            List<String> deleteList;
            if (null == menuList || menuList.isEmpty()) {
                //没有设置菜单信息，此时清空数据库
                deleteList = existsRoleMenuList;
            } else {
                final List<String> existsMenuList = getExistsMenu(menuList);
                //需要删除的
                deleteList = existsRoleMenuList.stream().filter(menuId -> !existsMenuList.contains(menuId)).collect(toList());
            }
            if (!deleteList.isEmpty()) {
                List<String> ids = menuIdToRoleMenuId(roleId, deleteList);
                removeBatchIds(ids);
            }
        }
        if (null != menuList && !menuList.isEmpty()) {
            final LocalDateTime now = LocalDateTime.now();
            final List<RoleMenu> roleMenuList = new ArrayList<>(menuList.size());
            menuList.forEach(menuId -> {
                RoleMenu roleMenu = getRoleMenuByRoleIdAndMenuId(roleId, menuId);
                if (null == roleMenu) {
                    roleMenu = new RoleMenu();
                    roleMenu.setRoleMenuId(IdWorker.getIdStr());
                    roleMenu.setRoleId(roleId);
                    roleMenu.setMenuId(menuId);
                    roleMenu.setAddTime(now);
                    roleMenuList.add(roleMenu);
                }
            });
            if (!roleMenuList.isEmpty()) {
                saveBatch(roleMenuList);
                roleMenuList.clear();
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleMenuRelations(RoleMenuRelationsDTO RoleMenuRelationsDTO) {
        final String roleId = RoleMenuRelationsDTO.getRoleId();
        final List<String> menuList = RoleMenuRelationsDTO.getMenuList();
        final List<String> existsMenu = getExistsMenu(menuList);
        if (!existsMenu.isEmpty()) {
            final List<String> roleMenuIdList = menuIdToRoleMenuId(roleId, existsMenu);
            if (!roleMenuIdList.isEmpty()) {
                removeBatchIds(roleMenuIdList);
                roleMenuIdList.clear();
            }
        }
    }

    private List<String> getExistsMenu(List<String> menuList) {
        final List<String> existsMenuList = menuService.getBaseMapper().getIds(menuList);
        if (existsMenuList.isEmpty()) {
            throw new ApiException("菜单信息不存在" + Arrays.toString(menuList.toArray()));
        }
        if (menuList.size() != existsMenuList.size()) {
            throw new ApiException("菜单信息不存在" + Arrays.toString(menuList.stream().filter(menuId -> !existsMenuList.contains(menuId)).toArray()));
        }
        return existsMenuList;
    }

    private List<String> menuIdToRoleMenuId(String roleId, List<String> menuList) {
        return menuList.stream().map(menuId -> {
            RoleMenu roleMenu = getRoleMenuByRoleIdAndMenuId(roleId, menuId);
            if (null != roleMenu) {
                return roleMenu.getRoleMenuId();
            }
            return null;
        }).filter(StringUtils::hasLength).collect(toList());
    }
}